<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .active {
            background-color: blue;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="control">
            <button>选项1</button>
            <button>选项2</button>
            <button>选项3</button>
        </div>
        <div class="content">
            <div class="box">内容1</div>
            <div class="box">内容2</div>
            <div class="box">内容3</div>
        </div>
    </div>
    <script>
        //先创建一个构造函数,把类名进行传参
        function fun(btns_selector, contents_selector) {
            this.btns = document.querySelectorAll(btns_selector)
            this.contents = document.querySelectorAll(contents_selector)
            this.index = 0
            this.clickBtn()
            this.changeContent()

        }
        fun.prototype.clickBtn = function () {
            //定义一个变量把实例对象的this给存储起来
            var self = this
            this.btns[0].className = 'active'
            for (let i = 0; i < this.btns.length; i++) {
                // 实例对象调用btns对象，然后给对象添加属性index
                this.btns[i].index = i
                this.btns[i].onclick = function () {
                    //排他思想
                    for (let k = 0; k < self.btns.length; k++) {
                        self.btns[k].className = ''
                    }
                    this.className = 'active'
                    self.index = this.index
                    self.changeContent()
                }
            }
        }

        //选项卡的内容显示
        fun.prototype.changeContent = function () {
            for (let j = 0; j < this.contents.length; j++) {
                this.contents[j].style.display = 'none'
            } this.contents[this.index].style.display = 'block'
        }
        var table = new fun(".control button", ".box")
        console.log(table.index)
    </script>
</body>

</html>